import Axios from "axios";
import { Loading, Message } from "element-ui";
const baseURL = "";
let loading = "";
var loadingNum = 0; // 监听接口数量， 为0关掉loading
class HttpRequest {
  constructor(baseUrl = baseURL) {
    this.baseUrl = baseUrl;
    this.queue = {};
  }
  getInsideConfig() {
    const config = {
      baseURL: this.baseUrl,
      header: {
      }
    };
    return config;
  }
  destroy(url) {
    delete this.queue[url];
    if (!Object.keys(this.queue).length) {
      // loading...
    }
  }
  interceptors(instance) {
    instance.interceptors.request.use(async config => { // 添加请求拦截
      loadingNum++;
      if (!config.data || (config.data && !(config.data.noLoading))) { // 请求接口需要loading效果
        loading = Loading.service({
          fullscreen: true,
          text: "Loading",
          spinner: "el-icon-loading",
          background: "rgba(0, 0, 0, 0.7)",
          customClass: "loading-z-index"
        });
      }
      const Usertoken = JSON.parse(sessionStorage.getItem("Usertoken"));
      if (Usertoken) {
        // 手动在Header中设置token
        config.headers.common["Authorization"] = Usertoken;
      }
      if (config.contentTypes) config.headers["Content-Type"] = config.contentTypes;
      else config.headers["Content-Type"] = " application/x-www-form-urlencoded";
      if (config.method.toLowerCase() === "post") {
        console.log("post");
      } else if (config.method.toLowerCase() === "get") {
        config.params = Object.assign({}, config.data);
      }
      return config;
    }, error => {
      loading.close();
      Message.error("网络出错，请稍后再试！");
      return Promise.reject(error);
    });
    instance.interceptors.response.use(res => { // 添加响应拦截
      const { status, data } = res;
      loadingNum--;
      if (loadingNum == 0 && loading !== "") {
        loading.close();
      }
      // 二进制数据则直接返回(文件导出数据)
      if (res.request.responseType === "blob" || res.request.responseType === "arraybuffer") {
        return res.data;
      }
      if (status === 200) {
        if (data.successful || data.code === 200) {
          return data.data;
        } else {
          Message.error(data.msg);
          return Promise.reject(data.msg);
        }
      } else {
        Message.error("网络出错");
        return Promise.reject("网络出错");
      }
    }, error => {
      loadingNum = 0;
      loading.close();
      Message.error("网络出错，请稍后再试！");
      return Promise.reject(error);
    });
  }
  request(options) {
    const instance = Axios.create();
    options = Object.assign(this.getInsideConfig(), options);
    this.interceptors(instance, options.url);
    return instance(options);
  }
}

const videoAxios = new HttpRequest();
export default videoAxios;
